package branch;

import fileoperation.FileCreation;
import gitobject.*;
import gitobject.GitObject;
import repository.Repository;
import java.io.*;


public class Branch {
    private final String key;
    private final String name;
    public static String path;

    static {
        try {
            path = Repository.getGitDir() + File.separator + "refs"+ File.separator+ "heads";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * Constructing branch object from a commit
     */
    public Branch(Commit commit) throws IOException{
        name = getCurrentBranchName();
        key = commit.getKey();
    }

    /**
     * Constructing branch from branch name
     */
    public Branch(String branch_name) throws IOException{
        name = branch_name;
        key = getCurrentCommitKey();
    }

    public String getKey(){
        return key;
    }
    public String getName(){
        return name;
    }

    /**
     * return current branch name
     */
    public static String getCurrentBranchName() throws IOException {
        File HEAD = new File(Repository.getGitDir() + File.separator + "HEAD");
        String path = GitObject.getValue(HEAD).substring(5).replace("\n", "");
        String[] paths = path.split("[\\\\/]");
        return paths[paths.length - 1];
    }

    /**
     * return current commit hash
     */
    public static String getCurrentCommitKey() throws IOException {
        File branch = new File(Branch.path + File.separator + getCurrentBranchName());
        return GitObject.getValue(branch);
    }

    /**
     * update file:HEAD
     */
    public static void updateHEAD(String branchName) throws Exception {
        File HEAD = new File(Repository.getGitDir() + File.separator + "HEAD");
        FileOutputStream fos = new FileOutputStream(HEAD);
        String HEADContent = "ref: refs"+ File.separator + "heads" +File.separator+branchName;
        byte[] content = HEADContent.getBytes();
        fos.write(content);
        fos.close();
    }

    /**
     * write commit hash to local
     */
    public void writeBranch()throws IOException {
        FileCreation.createFile(path, name, key);
    }

    /**
     * return if branch exist
     */
    public static boolean branchExist(String branchName) {
        File heads = new File(Branch.path);
        File[] file_list = heads.listFiles();
        assert file_list != null;
        for (File file : file_list) {
            if (file.getName().equals(branchName)) {
                return true;
            }
        }
        return false;
    }
}
